<?php

namespace Common\Model;

use Think\Model;

class ArticlePraiseModel extends Model
{
    /**
     * 添加文章点赞
     * @param string $aid
     * @param string $uid
     * @return bool|string
     */
    protected function inc_praise($aid = '', $uid = '')
    {
        $map['aid'] = intval($aid);
        $map['uid'] = intval($uid);

        $praise = $this->where($map)->find();
        if (empty($praise)) {
            $this->add($map);
            $this->on_article_praise($aid, $uid);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 文章点赞
     * @param $aid
     * @param $uid
     * @return array
     * @throws \Exception
     */
    public function article_praise($aid, $uid)
    {
        $article = M('Article')->find($aid);
        if (empty($article)) {
            $ret['status']  = false;
            $ret['content'] = "参数错误";  // 文章不存在
            return $ret;
        }

        $r = $this->inc_praise($aid, $uid);  // 增加点赞记录
        if (!$r) {
            $ret['status']  = false;
            $ret['content'] = "你已经赞过了！";
            return $ret;
        } else {
            $ret['status']  = true;
            $ret['content'] = '点赞成功';
            $ret['count']   = D('Article')->get_praise($aid);  // 获取点赞数量
            return $ret;
        }
    }

    /**
     * 添加点赞
     * @param int $uid
     * @param int $aid
     * @return array
     */
    public function praise_add($uid, $aid)
    {
        if (!$this->create(compact('uid', 'aid'))) {
            $res['status'] = false;
            $res['msg'] = $this->getError();
            return $res;
        } else {
            $newid = $this->add();
            if (!$newid) {
                $res['status'] = false;
                $res['msg'] = '点赞失败';
                return $res;
            } else {
                $res['status'] = true;
                $res['msg'] = '点赞成功';
                return $res;
            }
        }
    }

    /**
     * 添加点赞行为
     * @param $aid
     * @param $uid
     */
    protected function on_article_praise($aid, $uid)
    {
        $article = M('Article')->find($aid);
        D('Article')->inc_praise($article['id']);  // 修改文章点赞数字段
        D('User')->inc_praise($article['uid']);  // 更新会员点赞总数
        D('UserTrack')->add_track($uid, $article['id'], 5);  // 写入个人动态
        D('Rank')->add_record('praise', $article['uid'], 1);  // 记录排行记录
    }
}